package kr.ac.kongju.gedl.cmmn.web;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.ac.kongju.gedl.attach.service.AttachFileService;
import kr.ac.kongju.gedl.attach.vo.AttachFileVO;
import kr.ac.kongju.gedl.board.service.BoardContentsService;
import kr.ac.kongju.gedl.board.vo.ContentsVO;
import kr.ac.kongju.gedl.code.service.CodeService;
import kr.ac.kongju.gedl.code.vo.CodeInfoVO;
import kr.ac.kongju.gedl.common.util.DateUtil;
import kr.ac.kongju.gedl.common.util.ListResultVO;
import kr.ac.kongju.gedl.item.vo.ItemLevelVO;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.support.SessionStatus;


import egovframework.rte.fdl.property.EgovPropertyService;

@Controller
public class NavigationController {
	
	/** EgovPropertyService */
    @Resource(name = "propertiesService")
    protected EgovPropertyService propertiesService;
    
    @Resource(name = "attachFileService")
    protected AttachFileService attachFileService;
    
    public static final String TYPE_IMAGE = "01";
	public static final String TYPE_MOVIE = "02";
	public static final String TYPE_THUMBNAIL = "03";
	public static final String TYPE_ATTACH_FILE = "04";
   
	
	@RequestMapping(value="/navigation.do")
	public String selectPage(@ModelAttribute("pageCode") String pageCode) throws Exception {
		
		String returnPage = propertiesService.getString(pageCode);
		
		return returnPage;
	}
	
	@RequestMapping("/validator.do")
	public String validate(){
		return "/common/validator";
	}
	
	@RequestMapping("/download.do")
	public void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		String contentsId = StringUtils.defaultIfBlank(request.getParameter("contentsId"), "");
		int attachFileSeq = Integer.parseInt(StringUtils.defaultIfBlank(request.getParameter("attachFileSeq"), "1"));
		boolean thumbnail = Boolean.parseBoolean(StringUtils.defaultIfBlank(request.getParameter("thumbnail"), "false"));
		
		AttachFileVO attachFile = new AttachFileVO();
		attachFile.setContentsId(contentsId);
		attachFile.setAttachFileSeq(attachFileSeq);
		
		attachFile =  attachFileService.retrieveAttachFile(attachFile);
		
		if(attachFile != null) {
			String fileName = attachFile.getAttachFileOriginNm();
			String imgDir = attachFile.getAttachFilePath();
			if(thumbnail) {
				imgDir = attachFile.getThumbnailImgPath();
			}
			String fileType = attachFile.getAttachFileTypeCd();
			File lm_oSystemFile = new File(imgDir);
			if (lm_oSystemFile.exists()) {
				long lm_lFileSize = lm_oSystemFile.length();
				FileInputStream lm_oFileInputStream = null;
				//ServletOutputStream lm_osFileStream = null;
				BufferedOutputStream bos = null;
				try {
					lm_oFileInputStream = new FileInputStream(lm_oSystemFile);
	
					// 웹서버의 CharacterEncoding으로 설정해야 한글이 깨지지 않는다.
					if (fileType.equals(TYPE_IMAGE) || fileType.equals(TYPE_THUMBNAIL)) {
						response.setHeader("Accept-Ranges", "bytes");
						response.setHeader("Pragma", "No-cache");
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Expires", "0");
						
					} else if (fileType.equals(TYPE_MOVIE)) {
						response.setHeader("Content-Disposition","filename="
								+ new String(fileName.getBytes("EUC-KR"),"ISO-8859-1") + "\";");
						response.setHeader("Content-Transfer-Encoding", "chunked");
						response.setHeader("Content-length", String.valueOf(lm_lFileSize));
						response.setHeader("Cache-Control", "no-cache");
						response.setHeader("Content-Type", "audio/mpeg");
					}else {
						response.addHeader("Content-Disposition", "attachment; filename=\""
							     + new String(fileName.getBytes("EUC-KR"),"ISO-8859-1") + "\";");
							   response.setHeader("Content-Transfer-Encoding", "binary;");
						response.setHeader("Content-Transfer-Encoding", "binary");
					}
					
					response.setContentLength((int) lm_lFileSize);
					//lm_osFileStream = response.getOutputStream();
					bos = new BufferedOutputStream(response.getOutputStream());
					int lm_iNumRead;
					byte buff[] = new byte[1024];
					while ((lm_iNumRead = lm_oFileInputStream.read(buff, 0,buff.length)) > 0) {
						bos.write(buff, 0, lm_iNumRead);
					}// while
					bos.flush();
				} catch (Exception ex) {
					// 알림 메시지 출력 (메시지 내용 수정하기)
					@SuppressWarnings("unused")
					Object[] lm_oArgs = { fileName + "[" + lm_oSystemFile.getName() + "]" };
				} finally {
					//if (lm_osFileStream != null) {
						//lm_osFileStream.close();
					//}
					//if (lm_oFileInputStream != null) {
						//lm_oFileInputStream.close();
					//}
					//if (bos != null) {
					//	bos.close();
					//}
				}
			} else { // 파일이 삭제되었거나, 데이터 베이스랑 물리적 파일이 일치하지 않는 경우
				// 알림 메시지 출력
				@SuppressWarnings("unused")
				Object[] lm_oArgs = { fileName + "[" + lm_oSystemFile.getName()
						+ "]" };
			}
		}
		
		
	}
	
	
	
}
